<template>
  <el-dialog :visible.sync="visible" top="20px" :title="!dataForm.id ? '添加' : '修改'" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="140px">
      <el-form-item prop="name" label="名称">
        <el-input v-model="dataForm.name" placeholder="名称"/>
      </el-form-item>
      <el-form-item label="排序值:" style="margin-bottom: 15px;">
        <el-input-number :max="20" :min="1" v-model="dataForm.sort"></el-input-number>
        值越小越靠前
      </el-form-item>
      <el-form-item label="图片:" style="margin-bottom: 15px;" v-if="!this.dataForm.id">
        <el-upload
                class="upload-demo"
                ref="upload"
                :action="uploadUrl()"
                :before-upload="beforeAvatarUploadDetail"
                :file-list="fileList"
                :limit="1"
                :data="dataType"
                :headers="headers()"
                :on-success="handleSuccessDetail">
          <el-button slot="trigger" size="small" type="primary">选择图片</el-button>
          <div slot="tip" class="el-upload__tip">图片尺寸：1080px * 460px，只能上传一张png或jpg文件，且不超过1MB</div>
        </el-upload>
      </el-form-item>
      <el-form-item prop="remark" label="备注">
        <el-input v-model="dataForm.remark" placeholder="备注"/>
      </el-form-item>

    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { debounce } from 'lodash'
import Cookies from 'js-cookie'
// import { cookieGet } from '@/common/cookie'

let tokenStr = Cookies.get('token');

export default {
  data () {
    return {
      visible: false,
      fileList: [],
      dataType:{
        type: 'IMG'
      },
      dataForm: {
        id: '',
        type:1,
        name: '',
        status: 1,
        sort: 1,
        url: '',
        remark: ''
      }
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        unifiedSocialCreditCode: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        // this.$refs.upload.clearFiles()
        this.$refs['dataForm'].resetFields()
        Promise.all([

        ]).then(() => {
          if (this.dataForm.id) {
            this.getInfo()
          }
        })
      })
    },

    headers(){
      return{
        'token': tokenStr
      }
    },

    // 获取信息
    getInfo () {
      this.$axios.get(`/manager/banner/info/${this.dataForm.id}`).then(res => {
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http.json('/banner/addOrUpdate', this.dataForm).then(res => {
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false }),

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },

    beforeAvatarUploadDetail (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png';

      const isLt2M = file.size < 1024 * 1024

      if (!isJPG) {
        this.$message.error('上传图片只能是 PNG或JPEG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return isJPG && isLt2M;
    },
    uploadUrl () {
      return process.env.VUE_APP_API + "/file/upload"
    },

    //文件上传成功返回文件路径
    handleSuccessDetail (response, file, fileList) {
      if (response.code === 100) {
        this.dataForm.url = response.data
      } else {
        this.$message.error(response.msg)
      }
    },

  }
}
</script>
